import React from "react";
import { Card } from "antd";
// import Link from "umi/link";
// import queryString from 'query-string';
import { connect } from "dva";
import dynamic from 'umi/dynamic';
import styles from "./index.less";
import { openNotificationWithIcon, delay } from '../../../utils/comm';

import BasePage from './components/BasePage';
import TableList from '../../../components/tablelist/TableList';
import QueryExtra from './components/QueryExtra';
import AdvancedFilter from './components/AdvancedFilter';
import Catalogue from "../../../components/catalogue/Catalogue";
import PageLayout from "../../../components/pageconlayout/PageLayout";
import DealForm from '../../../components/processDealForm';
import RollbackForm from '../../../components/rollbackForm';

const CustomForm = dynamic({ loader: async () => {
  await delay(800);
  return import('../../../components/customForm/CustomForm');
} });

const emptyParams = {
  searchName: '',
  timeStart: '', // 开始时间
  timeEnd: '', // 结束时间
  applyUserName: '', // 申请人
  processStatus: '', // 处理状态 executing:执行中,completed:已完成
}

@connect(({
  FlowHandle, loading, appListMenu, Public,
}) => ({
  flowHandleStore: FlowHandle, loading,
  focusApp: appListMenu.focusApp,
  menuDataList: Public.menuDataList,
  resourceList: Public.resourceList,
}))
class FlowHandle extends BasePage {
  state = {
    filterVisible: false,
    visible: false,
    formVisible: false,
    rollbackVisible: false,
    selectedKeys: ['todo'],
    page: {
      pageNum: 1,
      pageSize: 6,
    },
  };

  openNotificationWithIcon = openNotificationWithIcon.bind(this);

  processType = 'todo'; // 我的流程单

  searchParams = emptyParams;

  componentDidMount() {
    this.initData();
  }

  componentDidUpdate(preProps) {
    const { focusApp } = this.props;
    const { focusApp: preFocusApp } = preProps;
    if (preFocusApp.id && `${preFocusApp.id || 0}` !== `${focusApp.id || 0}`) {
      // 应用切换更新页面数据
      this.resetPageData();
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: "FlowHandle/clearData" });
  }

  getFormThis = (formThis, type = 'advancedFilter') => {
    if (type === 'advancedFilter') {
      this.filterForm = formThis;
    } else if (type === 'queryExtra') {
      this.queryExtraForm = formThis;
    }
  }

  resetPageData = () => {
    const { dispatch } = this.props;
    this.searchParams = emptyParams;
    if (this.filterForm) this.filterForm.handleReset();
    if (this.queryExtraForm) this.queryExtraForm.handleReset();
    dispatch({ type: "FlowHandle/clearData" });
    this.setState({ page: { pageNum: 1, pageSize: 6 }, filterVisible: false, selectedKeys: ['todo'] }, () => {
      this.initData();
    });
  }

  /* 我的流程单选择 */
  handleTypeSelect = (data = []) => {
    this.processType = data.length > 0 ? data[0] : '';
    // 清除查询条件
    this.searchParams = emptyParams;
    if (this.filterForm) this.filterForm.handleReset();
    if (this.queryExtraForm) this.queryExtraForm.handleReset();
    this.setState({ selectedKeys: data });
    this.handleSearch();
  }

  // 查询参数改变
  handleParamsChange = (newparams) => {
    this.searchParams = { ...this.searchParams, ...newparams }
  }

  handleFilterVisible = () => {
    const { filterVisible } = this.state;
    this.setState({ filterVisible: !filterVisible });
  }

  handleDealFormVisible = (visible, record = '', isQuery = false) => {
    const { formKey } = record || {};
    this.record = record;
    this.disable = false;
    this.title = '处理任务';
    if (formKey) {
      this.customFormVisible(visible, record, isQuery);
      return;
    }
    this.setState({ visible });
    if (isQuery) {
      this.handleSearch();
    }
  }

  // 签收
  handleTaskclaim = (record = {}) => {
    const { dispatch } = this.props;
    const { taskId } = record;
    dispatch({ type: "FlowHandle/handleTaskclaim", payload: { taskId } }).then(({ errCode }) => {
      if (errCode === 0) {
        this.handleSearch();
      }
    });
  }

  customFormVisible = (status, record = '', isQuery = false) => {
    const { dispatch } = this.props;
    this.record = record;
    this.setState({ formVisible: status });
    if (status === true) {
      this.handleTaskForm(record);
    } else {
      dispatch({ type: "FlowHandle/get/taskform", payload: [] });
    }
    if (isQuery) {
      this.handleSearch();
    }
  }

  handleTaskForm = (record) => {
    const { taskId, formKey, processDefinitionId } = record || {};
    const { dispatch } = this.props;
    dispatch({ type: "FlowHandle/getTaskform", payload: { taskId, formKey, processDefinitionId } }).then(({ errCode, errMsg }) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon('error', '', errMsg || '获取处理表单信息失败');
      }
    });
  };

  // 动态表单填写保存
  handleFormSave = (values = {}) => {
    const { taskId } = this.record;
    const { dispatch } = this.props;
    const params = { variables: values, taskId };
    dispatch({ type: "FlowHandle/handleTask", payload: params }).then(({ errCode, errMsg }) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon('error', '', errMsg || '任务处理失败');
      } else {
        this.customFormVisible(false, '', true);
      }
    });
  };

  // 退回弹窗
  handleRollbackVisible = (visible, record = '', isQuery = false) => {
    const { taskId } = record || {};
    this.record = record;
    this.taskId = taskId;
    this.setState({ rollbackVisible: visible });
    if (isQuery) {
      this.handleSearch();
    }
  }

  render() {
    const { flowHandleStore, loading, dispatch } = this.props;
    const {
      page: { pageNum, pageSize },
      filterVisible, visible, selectedKeys, formVisible,
      rollbackVisible,
    } = this.state;
    const { processData = [], totalCount = 0, taskformFields = [] } = flowHandleStore;
    const listLoading = loading.effects[this.dispatchType[this.processType]];
    const confirmLoading = loading.effects['FlowHandle/handleTask'];
    const formLoading = loading.effects['FlowHandle/getTaskform'];
    const rollbackLoading = loading.effects['FlowHandle/handleTaskRollback'];
    return (
      <div className={styles.root}>
        <PageLayout
          leftClassName={styles.handle__left}
          leftContent={
            <Card
              title='我的流程单'
              style={{ width: '100%', height: '100%' }}
              bodyStyle={{ minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104 }}
            >
              <Catalogue
                CatalogueData={this.CatalogueData}
                treeNodeSelect={this.handleTypeSelect}
                defaultSelectedKeys={[this.processType]}
                selectedKeys={selectedKeys}
              />
            </Card>
          }
          rightContent={
            <Card
              title={`流程列表（${totalCount}）`}
              extra={
                <QueryExtra
                  handleParamsChange={this.handleParamsChange}
                  onSearch={this.handleSearch}
                  visible={filterVisible}
                  getFormThis={this.getFormThis}
                  handleFilterVisible={this.handleFilterVisible}
                />
              }
              bodyStyle={{ minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104 }}
              style={{ width: '100%' }}
            >
              <AdvancedFilter
                onSearch={this.handleSearch}
                handleParamsChange={this.handleParamsChange}
                visible={filterVisible}
                getFormThis={this.getFormThis}
                selectedKeys={selectedKeys}
              />
              <TableList
                dataSource={processData}
                loading={listLoading}
                columns={this.getColumns()}
                titleName='modelName'
                operationName='opration'
                onPageChange={this.handlePageChange}
                rowKey='taskId'
                className={styles.listcon}
                pagination={{
                  showQuickJumper: true,
                  showSizeChanger: true,
                  pageSizeOptions: ['6', '10', '20', '30'],
                  current: pageNum,
                  pageSize,
                  total: totalCount,
                }}
              />
            </Card>
          }
        />
        {visible && (
          <DealForm
            title={this.title}
            visible={visible}
            handleCancel={this.handleDealFormVisible}
            dispatch={dispatch}
            data={this.record || {}}
            disable={this.disable}
            taskId={(this.record || {}).taskId || ''}
            confirmLoading={confirmLoading}
          />
        )}
        {formVisible && (
          <CustomForm
            title={this.title}
            visible={formVisible}
            confirmLoading={false}
            onOk={(values) => { this.handleFormSave(values) }}
            onCancel={() => { this.customFormVisible(false) }}
            formConfigData={taskformFields}
            dataLoading={formLoading}
          />
        )}
        {rollbackVisible && (
          <RollbackForm
            visible={rollbackVisible}
            confirmLoading={rollbackLoading}
            onCancel={this.handleRollbackVisible}
            dispatch={dispatch}
            data={this.record}
          />
        )}
      </div>
    );
  }
}

export default FlowHandle;